const CACHE_PREFIX = "squirrel_"; // 防止与其他小程序或插件的key冲突

interface CacheData<T> {
  value: T;
  expire?: number; // 过期时间戳
}

class Cache {
  private getKey(key: string): string {
    return CACHE_PREFIX + key;
  }

  /**
   * 设置缓存
   * @param key 键
   * @param value 值
   * @param expireSeconds 过期时间，单位秒。不传或0表示永不过期
   */
  set<T>(key: string, value: T, expireSeconds?: number) {
    const cacheKey = this.getKey(key);
    const data: CacheData<T> = { value };
    if (expireSeconds && expireSeconds > 0) {
      data.expire = Date.now() + expireSeconds * 1000;
    }
    try {
      wx.setStorageSync(cacheKey, JSON.stringify(data));
    } catch (e) {
      console.error(`缓存写入失败：${key}`, e);
    }
  }

  /**
   * 获取缓存
   * @param key 键
   * @returns 缓存值，如果过期或不存在则返回 undefined
   */
  get<T>(key: string): T | "" {
    const cacheKey = this.getKey(key);
    try {
      const dataStr = wx.getStorageSync(cacheKey);
      if (!dataStr) return "";

      const data: CacheData<T> = JSON.parse(dataStr);
      if (data.expire && Date.now() > data.expire) {
        // 已过期，移除并返回undefined
        this.remove(key);
        return "";
      }
      return data.value;
    } catch (e) {
      console.error(`缓存读取失败或解析错误：${key}`, e);
      // 发生错误时，清理可能损坏的缓存
      this.remove(key);
      return "";
    }
  }

  /**
   * 移除缓存
   * @param key 键
   */
  remove(keys: string[]) {
    try {
      keys.forEach((key) => {
        const cacheKey = this.getKey(key);
        wx.removeStorageSync(cacheKey);
      });
      console.log("指定缓存已清空");
    } catch (e) {
      console.error(`缓存移除失败`, e);
    }
  }

  /**
   * 清空所有应用相关的缓存
   */
  clearAll() {
    try {
      const info = wx.getStorageInfoSync();
      info.keys.forEach((key) => {
        if (key.startsWith(CACHE_PREFIX)) {
          wx.removeStorageSync(key);
        }
      });
      console.log("所有应用缓存已清空");
    } catch (e) {
      console.error("清空缓存失败", e);
    }
  }
}

export const cache = new Cache();
